package org.utils.common;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;

public class EnhancedException extends Exception //RuntimeException
{
	private static final long serialVersionUID = 4790510860216799610L;

	private static final String DEFAULT_MESSAGE = "Erreur : {0}";

	protected static String getDefaultMessage()
	{
		return DEFAULT_MESSAGE;
	}

	/**
	 * Method formatMessage.
	 * @param arg1
	 * @param arg2
	 */
	protected static String formatMessage(String pMessage, String arg1)
	{
		Object[] args = {
			arg1
		};
		return MessageFormat.format(pMessage, args);
	}
	/**
	 * Method formatMessage.
	 * @param arg1
	 * @param arg2
	 */
	protected static String formatMessage(String pMessage, String arg1, String arg2)
	{
		Object[] args = {
			arg1,
			arg2
		};
		return MessageFormat.format(pMessage, args);
	}
	/**
	 * Method formatMessage.
	 * @param arg1
	 * @param arg2
	 */
	protected static String formatMessage(String pMessage, String arg1, String arg2, String arg3)
	{
		Object[] args = {
			arg1,
			arg2,
			arg3
		};
		return MessageFormat.format(pMessage, args);
	}

	private Throwable inner = null;
	
	public EnhancedException(Throwable t)
	{
	    this(t.toString(), t);
	}

	public EnhancedException(String msg, Throwable t)
	{
	    super(msg);
		inner = t;
	}

	public EnhancedException(String msg)
	{
	    super(msg);
	}

	public Throwable getThrowable()
	{
	    return inner;
	}
	
	public String toCompleteString(boolean includeStackTrace)
	{
	    StringBuffer buffer = new StringBuffer();
	    buffer.append(toString());
	    buffer.append(System.getProperty("line.separator"));
	    buffer.append("Inner Exception:");
	    buffer.append(System.getProperty("line.separator"));
	    if (includeStackTrace)
			buffer.append(getInnerStackTrace());
	    return buffer.toString();
	}
	
	public String getStackTraceOutput()
	{
	    StringWriter sw = new StringWriter();
	    printStackTrace( new PrintWriter(sw) );
	    return sw.toString();		
	}
	
	public String getInnerStackTrace()
	{
	    if (inner == null)
	    	return "";
	    StringWriter sw = new StringWriter();
	    inner.printStackTrace( new PrintWriter(sw) );
	    return sw.toString();		
	}
	/**
	 * @see java.lang.Throwable#printStackTrace(PrintStream)
	 */
	public void printStackTrace(PrintStream stream)
	{
		super.printStackTrace( stream );
		if (inner == null)
			return ;
	    stream.println("Inner Exception is :");
		inner.printStackTrace( stream );
	}
	/**
	 * @see java.lang.Throwable#printStackTrace(PrintWriter)
	 */
	public void printStackTrace(PrintWriter writer)
	{
		super.printStackTrace( writer );
		if (inner == null)
			return ;
	    writer.println("Inner Exception is :");
		inner.printStackTrace( writer );
	}
}